<template>
  <a-drawer
    :title="formInfo.id == undefined ? '新增' : '修改'"
    :maskClosable="true"
    width="80%"
    placement="right"
    :closable="true"
    @close="handleCancel"
    :destroyOnClose="true"
    :visible="visible"
    style="height: calc(100% - 55px); overflow: auto; padding-bottom: 53px"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model
        ref="ruleForm"
        :model="formInfo"
        :label-col="$global.labelCol"
        :wrapper-col="$global.wrapperCol"
      >
        <a-row>
          <a-col>
            <a-form-model-item
              label="模板名称"
              prop="templateName"
              :rules="$valid.required"
              :label-col="{ span: 6 }"
              :wrapper-col="{ span: 16 }"
            >
              <a-input
                v-model="formInfo.templateName"
                placeholder="请输入模板名称"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col>
            <a-form-model-item
              label="质控模板类型"
              prop="qualityTemplateType"
              :rules="$valid.required"
              :maxLength="50"
              :label-col="{ span: 6 }"
              :wrapper-col="{ span: 16 }"
            >
              <a-radio-group
                v-model="formInfo.qualityTemplateType"
                style="line-height: 35px"
              >
                <a-radio
                  v-for="item in this.$sysDictOptions('quality_template_type')"
                  :key="item.k"
                  :value="item.k"
                  class="radio-item"
                  >{{ item.v }}</a-radio
                >
              </a-radio-group>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-divider orientation="left">项目 </a-divider>
        <a-table
          :columns="contractPaymentTermColumns"
          :dataSource="qualityControlTemplateProjectList"
          :pagination="false"
          bordered
          size="middle"
          rowKey="key"
        >
          <!-- 自定义单元格渲染 - 可编辑单元格 v-for="(row, index) in data" -->
          <template
            v-for="col in editableContractPaymentTermColumns"
            :slot="col.dataIndex"
            slot-scope="text, record, index"
          >
            <div :key="col.dataIndex" class="editable-cell">
              <a-select
                v-if="col.dataIndex == 'status'"
                v-model="record[col.dataIndex]"
                placeholder="请选择"
                :class="{
                  'error-field': record.errors && record.errors[col.dataIndex],
                }"
              >
                <a-select-option key="0" value="0"> 否 </a-select-option>
                <a-select-option key="1" value="1"> 是 </a-select-option>
              </a-select>

              <a-input
                v-else-if="col.dataIndex == 'projectDesc'"
                type="textarea"
                v-model="record[col.dataIndex]"
                :min="0"
                placeholder="请输入"
                :class="{
                  'error-field': record.errors && record.errors[col.dataIndex],
                }"
              />
              <a-input
                v-else
                v-model="record[col.dataIndex]"
                :min="0"
                :placeholder="
                  col.dataIndex == 'referenceValue' ? '例如：是/否' : '请输入'
                "
                :class="{
                  'error-field': record.errors && record.errors[col.dataIndex],
                }"
              />

              <div
                class="error-message"
                v-if="record.errors && record.errors[col.dataIndex]"
              >
                {{ record.errors[col.dataIndex] }}
              </div>
            </div>
          </template>

          <!-- 操作列 - 添加/删除行按钮 -->

          <template slot="action" slot-scope="text, record, index">
            <div class="action-buttons">
              <a-tooltip title="添加一行">
                <a-button
                  type="primary"
                  shape="circle"
                  icon="plus"
                  size="small"
                  @click="addContractPaymentTermRow(index)"
                  v-if="index === qualityControlTemplateProjectList.length - 1"
                  :disabled="hasContractPaymentTermErrors"
                />
              </a-tooltip>
              <a-tooltip title="删除此行" v-if="index != 0">
                <a-button
                  style="background-color: #d9d9d9"
                  type="default"
                  shape="circle"
                  icon="minus"
                  size="small"
                  @click="removeContractPaymentTermRow(index)"
                  v-if="
                    qualityControlTemplateProjectList.length > 1 &&
                    index === qualityControlTemplateProjectList.length - 1
                  "
                />
              </a-tooltip>
            </div>
          </template>
          <!-- 表头添加必填标识 -->
          <template slot="accessoryNameTitle" slot-scope="title">
            <span class="required-label">*</span>{{ title }}
          </template>
        </a-table>
      </a-form-model>
    </a-spin>
    <!-- class="drawer-bootom-button" -->
    <div style="display: flex; margin-top: 10%; justify-content: flex-end">
      <a-popconfirm
        title="确定放弃编辑？"
        @confirm="handleCancel"
        okText="确定"
        cancelText="取消"
      >
        <a-button style="margin-right: 0.8rem">取消</a-button>
      </a-popconfirm>

      <a-button @click="handleSubmit" type="primary" :loading="confirmLoading"
        >保存</a-button
      >
    </div>
  </a-drawer>
</template>

<script>
import { getAction, postAction, deleteAction } from '@/api/manage'

import { STable, Ellipsis } from '@/components'
import { getDepartTree } from '@/api/api'
export default {
  name: 'DevQualityTemplateEdit',
  components: { STable, Ellipsis },
  data() {
    return {
      archiveEquipmentVisible: false,
      visible: false,
      confirmLoading: false,
      formInfo: {
        createTime: undefined,
        qualityTemplateType: '0',
        templateName: undefined,
        wx: '',
      },
      url: {
        saveInfo: '/system/devQualityControlTemplate/save',
        getInfo: '/system/devQualityControlTemplate/info',
        saveApplicableEquipmentInfo:
          '/system/devQualityTemplateApplicableEquipment/save',
        getApplicableEquipmentInfo:
          '/system/devQualityTemplateApplicableEquipment/info',
        deleteApplicableEquipmentInfo:
          '/system/devQualityTemplateApplicableEquipment/delete',
        listApplicableEquipmentPage:
          '/system/devQualityTemplateApplicableEquipment/list',
      },

      contractPaymentTermColumns: [
        {
          title: '项目名称',
          dataIndex: 'projectName',
          scopedSlots: {
            customRender: 'projectName',
            title: 'projectNameTitle',
          },
        },
        {
          title: '项目参考值',
          dataIndex: 'referenceValue',
          scopedSlots: {
            customRender: 'referenceValue',
            title: 'referenceValueTitle',
          },
        },
        {
          title: '默认值',
          dataIndex: 'defaultValue',
          scopedSlots: {
            customRender: 'defaultValue',
          },
        },
        {
          title: '是否启用',
          dataIndex: 'status',
          scopedSlots: {
            customRender: 'status',
          },
        },
        {
          title: '描述',
          dataIndex: 'projectDesc',
          scopedSlots: {
            customRender: 'projectDesc',
          },
        },

        {
          title: '操作',
          dataIndex: 'action',
          width: '10%',
          scopedSlots: { customRender: 'action' },
        },
      ],
      qualityControlTemplateProjectList: [
        {
          key: Date.now().toString(),
          projectName: undefined,
          projectDesc: undefined,
          referenceValue: undefined,
          defaultValue: undefined,
          status: '1',
          errors: {},
        },
      ],
      selectedRowKeys: [],

      columns: [
        {
          title: '设备短码',
          dataIndex: 'deviceShortCode',
          width: 150,
        },
        {
          title: '设备名称',
          dataIndex: 'deviceName',
          width: 150,
        },
        {
          title: '品牌',
          dataIndex: 'bind',
          width: 150,
        },
        {
          title: '型号',
          dataIndex: 'model',
          width: 150,
        },
        {
          title: '使用科室',
          dataIndex: 'usingDepartmentId',
          width: 200,
          customRender: (text) => this.getUsingDepartmentId(text),
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 100,
          scopedSlots: { customRender: 'action' },
        },
      ],
      loadData: [],
      departmentTree: [],
    }
  },
  created() {
    this.getDepartment()
  },
  computed: {
    rowSelection() {
      return {
        // 选择类型：checkbox或者radio，默认是checkbox
        type: 'checkbox',
        // 选中的行键值，即每一行的key（这里我们使用id）
        selectedRowKeys: this.selectedRowKeys,
        // 选中项发生变化时的回调
        onChange: (selectedRowKeys, selectedRows) => {
          console.log('selectedRowKeys: ', selectedRowKeys)
          console.log('selectedRows: ', selectedRows)
          this.selectedRowKeys = selectedRowKeys
        },
        // 单独选中的行变化
        onSelect: (record, selected, selectedRows) => {
          console.log(record, selected, selectedRows)
        },
        // 全选变化
        onSelectAll: (selected, selectedRows, changeRows) => {
          console.log(selected, selectedRows, changeRows)
        },
      }
    },

    //开启选择
    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },

    editableApplicableEquipmentColumns() {
      return this.applicableEquipmentColumns.filter(
        (col) => col.dataIndex !== 'action'
      )
    },
    // 检查是否有错误
    hasApplicableEquipmentErrors() {
      return this.applicableEquipmentList.some(
        (row) => row.errors && Object.keys(row.errors).length > 0
      )
    },

    editableContractPaymentTermColumns() {
      return this.contractPaymentTermColumns.filter(
        (col) => col.dataIndex !== 'action'
      )
    },
    // 检查是否有错误
    hasContractPaymentTermErrors() {
      return this.qualityControlTemplateProjectList.some(
        (row) => row.errors && Object.keys(row.errors).length > 0
      )
    },
  },
  methods: {
    //使用科室
    getDepartment() {
      getDepartTree().then((res) => {
        this.departmentTree = res.result.data
      })
    },
    getUsingDepartmentId(text) {
      if (text) {
        var names = ''
        var usingDepartmentList = text.split(',')
        usingDepartmentList.forEach((usingDepartmentId) => {
          var value = this.getFindNodeByKey(
            this.departmentTree,
            usingDepartmentId
          )
          names = names + value.title + ','
        })
        if (names) {
          names = names.substring(0, names.length - 1)
        }
        console.log('value>>', names)
        return names
      }
    },
    getFindNodeByKey(tree, key) {
      console.log('XXXKey>', key)
      for (let i = 0; i < tree.length; i++) {
        if (tree[i].value === key) {
          return tree[i] // 找到匹配项，返回该节点
        } else if (tree[i].children) {
          // 递归搜索子节点
          const found = this.getFindNodeByKey(tree[i].children, key)
          if (found) return found // 如果在子节点中找到，返回该节点
        }
      }
      return null // 未找到匹配项
    },

    archiveEquipmentOpen() {
      this.archiveEquipmentVisible = true
    },

    archiveEquipmentClose() {
      this.archiveEquipmentVisible = false
    },

    getQualityControlTypeName(value, dictType) {
      if (value) {
        var dictList = this.$sysDictOptions(dictType)
        return dictList[`wx${value}`].v
      }
      return '--'
    },

    // 添加新行
    addContractPaymentTermRow(index) {
      if (this.hasContractPaymentTermErrors) return
      var indexOf = index + 1
      console.log('indexOf+1>>', indexOf + 1)
      this.qualityControlTemplateProjectList.splice(indexOf, 0, {
        key: Date.now().toString(),
        projectName: undefined,
        projectDesc: undefined,
        referenceValue: undefined,
        defaultValue: undefined,
        status: '1',
        errors: {},
      })
    },

    // 删除行
    removeContractPaymentTermRow(index) {
      this.qualityControlTemplateProjectList.splice(index, 1)
    },

    add() {
      this.qualityControlTemplateProjectList = [
        {
          key: Date.now().toString(),
          projectName: undefined,
          projectDesc: undefined,
          referenceValue: undefined,
          defaultValue: undefined,
          status: '1',
          errors: {},
        },
      ]

      this.edit()
    },
    edit(record) {
      this.$objToOverride(this.formInfo, record)
      if (this.formInfo.id) {
        getAction(this.url.getInfo, { id: record.id }).then((res) => {
          this.$nextTick(() => {
            this.formInfo = res.result.data
            if (this.formInfo.qualityControlTemplateProject) {
              this.qualityControlTemplateProjectList = JSON.parse(
                this.formInfo.qualityControlTemplateProject
              )
            }
          })
        })
      }
      this.visible = true
    },
    // 确定
    handleSubmit() {
      // 触发表单验证
      this.confirmLoading = true
      this.$refs.ruleForm.validate((valid) => {
        console.log(valid)
        if (valid) {
          if (this.qualityControlTemplateProjectList) {
            this.formInfo.qualityControlTemplateProject = JSON.stringify(
              this.qualityControlTemplateProjectList
            )
          } else {
            this.$message.error('请填写项目信息')
          }
          postAction(this.url.saveInfo, this.formInfo)
            .then((res) => {
              this.$message.success(res.content)
              this.$emit('ok', this.formInfo)
              this.close()
            })
            .finally(() => {
              this.confirmLoading = false
            })
        } else {
          this.confirmLoading = false
        }
      })
    },

    // 关闭
    handleCancel() {
      this.close()
    },
    close() {
      this.$refs.ruleForm.resetFields()
      this.$objToReset(this.formInfo)
      this.$emit('close')
      this.visible = false
    },
  },
}
</script>
<style scoped>
.ant-input[disabled] {
  margin-top: 3px;
  background-color: #fff !important;
  border: none !important;
  color: rgba(0, 0, 0, 0.65) !important;
  cursor: not-allowed;
}
.ant-input {
  padding-left: 5px;
}

.span-line-height {
  line-height: 38px;
}
</style>
